<template>
  <view class="mine-container" :style="{ height: `${windowHeight}px` }">
    <!--顶部个人信息栏-->
    <view class="header-section">
      <view class="flex padding justify-between">
        <view class="flex align-center">
          <view v-if="!avatar" class="cu-avatar xl round bg-white">
            <view class="iconfont icon-people text-gray icon"></view>
          </view>
          <image v-if="avatar" @click="handleToAvatar" :src="avatar" class="cu-avatar xl round" mode="widthFix">
          </image>
          <view v-if="!name" @click="handleToLogin" class="login-tip">
            {{ userStore && userStore.userInfo ? `${userStore.userInfo.username}` : "点击登录" }}
          </view>
          <view v-if="name" @click="handleToInfo" class="user-info">
            <view class="u_title">
              用户名：{{ name }}
            </view>
          </view>
        </view>
        <view @click="handleToInfo" class="flex align-center">
          <text>个人信息</text>
          <view class="iconfont icon-right"></view>
        </view>
      </view>
    </view>

    <view class="content-section">

      <!-- 商家 -->
      <view class="mine-actions grid col-4 text-center" v-if="userLevel == 1">
        <view style="display: block; justify-content: center; display:flex; align-items:center;">商家特权: </view>
        <view class="action-item" @click="handleRecordSeller(1)">
          <img class="topImg" src="@/assets/mine/sendFood.svg">
          <text class="text">待出餐</text>
          <text class="num">{{ waitSendSeller }}</text>
        </view>
        <view class="action-item" @click="handleRecordSeller(2)">
          <img class="topImg" src="@/assets/mine/sendFinally.svg">
          <text class="text">待送达</text>
          <text class="num">{{ waitSendFood }}</text>
        </view>
        <view class="action-item" @click="handleRecordSeller(3)">
          <img class="topImg" src="@/assets/mine/reFund.svg">
          <text class="text">待退款</text>
          <text class="num">{{ 0 }}</text>
        </view>
      </view>

      <!-- 用户 -->
      <view class="mine-actions grid col-4 text-center">
        <view class="action-item" @click="handleRecord(1)">
          <img class="topImg" src="@/assets/mine/waitPay.svg">
          <text class="text">待付款</text>
          <text class="num">{{ waitPay }}</text>
        </view>
        <view class="action-item" @click="handleRecord(2)">
          <img class="topImg" src="@/assets/mine/sendFood.svg">
          <text class="text">待出餐</text>
          <text class="num">{{ departFood }}</text>
        </view>
        <view class="action-item" @click="handleRecord(3)">
          <img class="topImg" src="@/assets/mine/getFood.svg">
          <text class="text">待取餐</text>
          <text class="num">{{ waitTakeFood }}</text>
        </view>
        <view class="action-item" @click="handleRecord(4)">
          <img class="topImg" src="@/assets/mine/remark.svg">
          <text class="text">待评价</text>
          <text class="num">{{ waitRemark }}</text>
        </view>
      </view>

      <view class="menu-list">
        <view class="list-cell list-cell-arrow" @click="handleToEditInfo">
          <view class="menu-item-box">
            <view class="iconfont icon-user menu-icon"></view>
            <view>编辑资料</view>
          </view>
        </view>
        <view v-if="userLevel == 1" class="list-cell list-cell-arrow" @click="handleUpFood">
          <view class="menu-item-box">
            <view class="iconfont icon-service menu-icon"></view>
            <view>餐品管理</view>
          </view>
        </view>
        <view v-if="userLevel == 0 || userLevel == 1" class="list-cell list-cell-arrow" @click="handleJoinStore">
          <view class="menu-item-box">
            <view class="iconfont icon-service menu-icon"></view>
            <view>商家入驻</view>
          </view>
        </view>
        <view v-if="userLevel == -1" class="list-cell list-cell-arrow" @click="handleAuditStore">
          <view class="menu-item-box">
            <view class="iconfont icon-service menu-icon"></view>
            <view>入驻审核</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleHelp">
          <view class="menu-item-box">
            <view class="iconfont icon-help menu-icon"></view>
            <view>常见问题</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleAbout">
          <view class="menu-item-box">
            <view class="iconfont icon-aixin menu-icon"></view>
            <view>关于我们</view>
          </view>
        </view>
        <view class="list-cell list-cell-arrow" @click="handleToSetting">
          <view class="menu-item-box">
            <view class="iconfont icon-setting menu-icon"></view>
            <view>应用设置</view>
          </view>
        </view>
      </view>

    </view>
  </view>
  <!-- <view>
	  <uni-popup ref="popup" type="dialog">
	    <uni-popup-dialog type="info" cancelText="关闭" confirmText="退出"
	                      title="通知" content="确定注销并退出系统吗" 
	    				  @confirm="dialogConfirm"
	                      @close="dialogClose">
	    </uni-popup-dialog>
	  </uni-popup>
  </view> -->
</template>

<script setup>
import { ref, onActivated } from "vue";
import config from '@/config.js'
import useUserStore from '@/store/modules/user'
import { searchAllOrder, searchSellerAllOrder } from "@/api/order";
import useOrderStore from "@/store/modules/order";
import { getUserInfo } from "@/api/user/index";
import { addSchool } from "@/api/school/index"

const userStore = useUserStore()
let orderStore = useOrderStore();
const name = userStore.name;
const version = config.appInfo.version;

const avatar = ref(userStore.userInfo?.avatar || '');
const windowHeight = ref(uni.getSystemInfoSync().windowHeight - 50);
const popup = ref(null);

uni.$on('refresh', () => {
  avatar.value = userStore.avatar || '';
})

console.log(avatar.value)

/**
 * 获取用户的身份等级
 */
let userLevel = ref(0)
if (userStore.userInfo && userStore.userInfo.user_level) {
  userLevel.value = userStore.userInfo.user_level
}

/**
 * 查询用户所有订单
 */
let allOrder = ref([])
let getInfo = () => {
  searchAllOrder({ userId: userStore.userId || '' }).then(res => {
    if (res.code == 200) {
      allOrder.value = res.data
      getCount(allOrder.value)
    }
  })
}
getInfo()

/**
 * 查询商家所有订单
 */
let sellerAllOrder = ref([])
let getSellerInfo = () => {
  searchSellerAllOrder({ sellerId: userStore.userId || '' }).then(res => {
    if (res.code == 200) {
      sellerAllOrder.value = res.data
      console.log('sellerAllOrder: ', sellerAllOrder);
      getSellerCount(sellerAllOrder.value)
    }
  })
}

if (userStore.userInfo && userStore.userInfo.user_level == 1) {
  getSellerInfo()
}


/**
 * 查询用户信息
 */
let getCurrentUserInfo = () => {
  getUserInfo({ userId: userStore.userId || '' }).then(res => {
    userStore.getInfo(res.userInfo)
    avatar.value = userStore.userInfo?.avatar || ''
  })
}
// 获取用户数据
getCurrentUserInfo()

// 监听页面激活
onActivated(() => {
  // 获取订单数据
  getInfo()
  // 获取用户数据
  getCurrentUserInfo()
  // 获取商家数据
  if (userStore.userInfo && userStore.userInfo.user_level == 1) {
    getSellerInfo()
  }
});

/**
 * 计算不同状态订单的数量(用户)
 */
let waitPay = ref(0)
let departFood = ref(0)
let waitTakeFood = ref(0)
let waitRemark = ref(0)
let getCount = (data) => {
  waitPay.value = 0
  departFood.value = 0
  waitTakeFood.value = 0
  waitRemark.value = 0
  data.forEach(order => {
    orderStatus(order.startTime, order.isPay, order.isSend, order.isReceive)
  });
}
/**
 * 计算不同状态订单的数量(商家)
 */
let waitSendSeller = ref(0) // 待出餐
let waitSendFood = ref(0) // 待送达
let getSellerCount = (data) => {
  waitSendSeller.value = 0
  waitSendFood.value = 0
  data.forEach(order => {
    orderStatusSeller(order.isSend, order.isReceive)
  });
}

/**
 * 判断当前订单的状态
 */
const orderStatus = (time, isPay, isSend, isReceive) => {
  const currentTime = new Date();
  const orderTime = new Date(Number(time));
  const timeDiff = (currentTime - orderTime) / (1000 * 60);

  if (timeDiff > 10 && !isPay) {
    return '超时';
  }

  if (!isPay) {
    waitPay.value += 1
    return
  }

  if (!isSend) {
    departFood.value += 1
    return
  }

  if (!isReceive) {
    waitTakeFood.value += 1
    return
  }
  waitRemark.value += 1
};

/**
 * 判断当前订单的状态
 */
const orderStatusSeller = (isSend, isReceive) => {

  if (!isSend) {
    waitSendSeller.value += 1
    return
  }

  if (!isReceive) {
    waitSendFood.value += 1
    return
  }
};





function handleToInfo() {
  uni.navigateTo({
    url: '/pages_mine/pages/info/index'
  });
};
function handleToEditInfo() {
  uni.navigateTo({
    url: '/pages_mine/pages/info/edit'
  });
};

/**
 * 商家入驻
 */
function handleJoinStore() {
  uni.navigateTo({
    url: '/pages_mine/pages/addStore/index'
  });
};
/**
 * 餐品管理
 */
function handleUpFood() {
  uni.navigateTo({
    url: '/pages_mine/pages/foodManage/index'
  });
};
/**
 * 入驻审核
 */
function handleAuditStore() {
  uni.navigateTo({
    url: '/pages_mine/pages/auditSeller/index'
  });
};

function handleToSetting() {
  uni.navigateTo({
    url: '/pages_mine/pages/setting/index'
  });
};
function handleToLogin() {
  uni.reLaunch({
    url: '/pages/login'
  });
};
function handleToAvatar() {
  // uni.navigateTo({
  //   url: '/pages_mine/pages/avatar/index'
  // });

  // addSchool(data).then(res => {

  // })
};
function handleLogout() {
  popup.value.open();
};
function dialogConfirm() {
  //console.log('----------------点击确认------------')

  userStore.logOut().then(() => {
    uni.reLaunch({
      url: '/pages/login'
    });
  })
};
function dialogClose() {
  //console.log('点击关闭')
};
function handleHelp() {
  uni.navigateTo({
    url: '/pages_mine/pages/help/index'
  });
};
function handleAbout() {
  uni.navigateTo({
    url: '/pages_mine/pages/about/index'
  });
};
function handleRecord(num) {
  uni.navigateTo({
    url: `/pages/orderRecord?currentTabIndex=${num}`
  });
};
function handleRecordSeller(num) {
  uni.navigateTo({
    url: `/pages/orderRecordSeller?currentTabIndex=${num}`
  });
};
function handleBuilding() {
  uni.showToast({
    title: '模块建设中~',
    mask: false,
    icon: "none",
    duration: 1000
  });
}

</script>

<style lang="scss" scoped>
page {
  background-color: #f5f6f7;
}

.mine-container {
  width: 100%;
  height: 100%;
  margin-bottom: 200rpx;

  .header-section {
    padding: 30rpx 30rpx 90rpx 30rpx;
    background-color: #3c96f3;
    color: white;

    .login-tip {
      font-size: 36rpx;
      margin-left: 20rpx;
    }

    .cu-avatar {
      border: 4rpx solid #eaeaea;

      .icon {
        font-size: 80rpx;
      }
    }

    .user-info {
      margin-left: 30rpx;

      .u_title {
        font-size: 36rpx;
        line-height: 60rpx;
      }
    }
  }

  .content-section {
    position: relative;
    top: -100rpx;

    .mine-actions {
      margin: 30rpx 30rpx;
      padding: 40rpx 0rpx;
      border-radius: 16rpx;
      background-color: white;

      .action-item {
        .icon {
          font-size: 56rpx;
        }

        .text {
          display: block;
          font-size: 26rpx;
          // margin: 16rpx 0rpx;
        }

        .num {
          display: block;
          font-size: 26rpx;
          font-weight: 600;
        }

        .topImg {
          width: 56rpx;
          height: 56rpx;
          margin: 10rpx 0;
        }
      }
    }
  }
}
</style>
